package com.sunyard.utils.Response;

import com.sunyard.constant.ErrMessageConst;
import com.sunyard.utils.ftputil.FileUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class HeaderResult {

    public static void setHeader(HttpServletRequest req, HttpServletResponse res, Exception e) {
        res.addHeader("datacode", "01");
        res.setHeader("Access-Control-Expose-Headers", "datacode");
        String message = null;
        try {
            message = FileUtils.encodeDownloadFilename(e.getMessage(), req.getHeader("user-agent"));
        } catch (IOException ioException) {
            log.error(ErrMessageConst.SYSTEM_ERROR, ioException);
        }
        res.addHeader("datamessage", message);
        res.setHeader("Access-Control-Expose-Headers", "datamessage");
    }

    public static void setSuccessHeader(HttpServletRequest req, HttpServletResponse res, String message) {
        res.addHeader("datacode", "00");
        res.setHeader("Access-Control-Expose-Headers", "datacode");
        try {
            message = FileUtils.encodeDownloadFilename(message, req.getHeader("user-agent"));
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        res.addHeader("datamessage", message);
        res.setHeader("Access-Control-Expose-Headers", "datamessage");
    }

    public static void setFailHeader(HttpServletRequest req, HttpServletResponse res, String message) {
        res.addHeader("datacode", "01");
        res.setHeader("Access-Control-Expose-Headers", "datacode");
        try {
            message = FileUtils.encodeDownloadFilename(message, req.getHeader("user-agent"));
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        res.addHeader("datamessage", message);
        res.setHeader("Access-Control-Expose-Headers", "datamessage");
    }

    public static void setExpireHeader(HttpServletRequest req, HttpServletResponse res, String message) {
        res.addHeader("datacode", "04");
        res.setHeader("Access-Control-Expose-Headers", "datacode");
        try {
            message = FileUtils.encodeDownloadFilename(message, req.getHeader("user-agent"));
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        res.addHeader("datamessage", message);
        res.setHeader("Access-Control-Expose-Headers", "datamessage");
    }

}
